package com.tm.controller;

import com.tm.pojo.MemberPojo;
import com.tm.service.MemberService;
import com.tm.SendSmsutil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Rocky
 * @create 2022-09-14 10:52
 */
@RestController
@RequestMapping("member")
public class MemberController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MemberService memberService;

    //发送验证码的接口
    @PostMapping("sendCode")
    public String sendCode(String phonenumber){
        String s = SendSmsutil.loginsendSms(phonenumber);
        redisTemplate.opsForValue().set("code_"+phonenumber,s,5,TimeUnit.MINUTES);
        return "获取成功";
    }

    //登录接口
    @PostMapping("userLogin")
    public String userLogin(MemberPojo memberPojo){
        String memberpwd = memberPojo.getMemberpwd();
        if (StringUtils.isNotBlank(memberpwd)){
            //查询数据库得到密码，然后判断密码是否一致
            MemberPojo memberPojo1= memberService.queryBypassword(memberPojo.getMemberaccount(),memberPojo.getMemberpwd());
            if (memberPojo1==null){
                return "账号或密码错误";
            }
            //验证通过之后生成一个token,将token存入到redis中；
            String s = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set("token_"+memberPojo.getMemberphonenumber(),s);
            return s;
        }

            Object o = redisTemplate.opsForValue().get("code_" +memberPojo.getMemberphonenumber());
            if (o==null){
                return "验证码已过期";
            }
        if (memberPojo.getMembercode().equals(o.toString())){
            String s = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set("token_"+memberPojo.getMemberphonenumber(),s);
            return s;
        }else {
            return "验证码错误";
        }

    }
}
